package Concurrency2.Chapter02_InnerLockPrinciple;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

import static utils.MUtils.print;

/**
 * Instruction：解决静态条件问题 - 使用内置锁synchronized
 * Author：@author MaLi
 */
public class T01_BiasedLock {
    private static /*volatile*/ int sharedNum = 0;  // 临界资源
    private static int TIMES = 10000;               // 每个线程累加次数
    private static int THREADS_QUANTITY = 10;       // 线程个数
    private static ArrayList<Thread> threads = new ArrayList<>(THREADS_QUANTITY);   //保存线程

    private static final Object lock = new Object();

    // 用于同步: THREADS_QUANTITY个线程全部执行完成, 放行主线程
    private static CountDownLatch countDownLatch = new CountDownLatch(10);

    public static void main(String[] args) {
        T01_BiasedLock some = new T01_BiasedLock();
        //创建线程
        for (int j = 0; j < THREADS_QUANTITY; j++) {
            Thread thread = new Thread(() -> {
                // 同步代码块
                //method1();
                // 同步方法
                //some.method2();
                // 静态同步方法
                method3();
                print("ThreadName" + Thread.currentThread().getName() + " 执行完毕");
                countDownLatch.countDown();
            });
            threads.add(thread);
        }
        //启动线程
        for (Thread thread : threads) {
            thread.start();
        }
        //主线程等待全部线程执行完毕, 输出计数结果
        try {

            countDownLatch.await();
            System.out.println("sharedNum :" + sharedNum);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    // 使用方法1 - 同步代码块
    private static void method1() {
        for (int i = 0; i < TIMES; i++) {
            synchronized (lock) {
                //sharedNum++;
                sharedNum = sharedNum + 1;
            }
        }
    }
    // 使用方法2 - 同步代码块
    private synchronized void method2() {
        for (int i = 0; i < TIMES; i++) {
            //sharedNum++;
            sharedNum = sharedNum + 1;
        }
    }

    // 使用方法3 - 静态同步方法
    private static synchronized void method3() {
        for (int i = 0; i < TIMES; i++) {
            //sharedNum++;
            sharedNum = sharedNum + 1;
        }
    }



}
